<script setup lang="ts">
import type { ConsultOrderItem } from '@/types/consult'
import { OrderType } from '@/enums'
import dayjs from 'dayjs'
import { ref, computed } from 'vue'
import { cancelConsultOrderService, deleteOrderService } from '@/api/consult'
import { Dialog, Toast } from 'vant'
import { useShowPrescription } from '@/composables/showPrescription'
import { useRouter } from 'vue-router'

const props = defineProps<{
  item: ConsultOrderItem
}>()
const emit = defineEmits<{
  (e: 'refreshList'): void
}>()

// 取消问诊
const loading = ref(false) // 防止重复点击
const cancelConsult = async (item: ConsultOrderItem) => {
  loading.value = true
  Dialog.confirm({
    title: '温馨提示',
    message: '您确定要取消问诊吗？',
  })
    .then(async () => {
      try {
        await cancelConsultOrderService(item.id)
        Toast.success({
          message: '取消成功',
        })
        // 刷新列表开销有点大，这里选择局部修改
        item.status = OrderType.ConsultCancel
        item.statusValue = '已取消'
      } catch (error) {
        console.log(error)
      } finally {
        loading.value = false
      }
    })
    .catch(() => {
      // 取消取消请求
      console.log('点击了取消')
      loading.value = false
    })
}

// == 已完成订单使用 ==
// 控制更多操作显示
const showPopover = ref(false)
// 操作项
const actions = computed(() => [
  { text: '查看处方', disabled: !props.item.prescriptionId }, // 没有开处方不能查看
  { text: '删除订单' },
])
// 操作项的点击回调
const onSelect = (action: { text: string; [key: string]: any }, item: ConsultOrderItem) => {
  // 点击了删除订单
  if (action.text === '删除订单') {
    deleteOrder(item)
  } else if (action.text === '查看处方') {
    showPrescription(item.prescriptionId!)
  }
}

// 删除订单
const deleteOrder = async (item: ConsultOrderItem) => {
  Dialog.confirm({
    title: '温馨提示',
    message: '您确定要删除订单吗？',
  })
    .then(async () => {
      try {
        await deleteOrderService(item.id)
        Toast.success('删除成功')
        emit('refreshList')
      } catch (error) {
        console.log(error)
      }
    })
    .catch(() => {
      // 取消删除请求
      console.log('点击了取消')
    })
}

// 查看处方
const { showPrescription } = useShowPrescription()

// 点击跳转详情
const router = useRouter()
const goDetail = (item: ConsultOrderItem) => {
  router.push(`/user/consult/${item.id}`)
}
</script>

<template>
  <div class="consult-item">
    <div class="head van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p>{{ item.docInfo?.name || '暂未分配医生' }}</p>
      <span
        :class="{
          orange: item.status === OrderType.ConsultPay,
          green: item.status === OrderType.ConsultChat,
        }"
        >{{ item.statusValue }}</span
      >
    </div>
    <!-- 患者信息 -->
    <div class="body" @click="goDetail(item)">
      <div class="body-row">
        <div class="body-label">患者</div>
        <div class="body-value tip">{{ item.patientInfo.name }}</div>
      </div>
      <div class="body-row">
        <div class="body-label">病情描述</div>
        <div class="body-value tip">{{ item.illnessDesc }}</div>
      </div>
      <div class="body-row">
        <div class="body-label">价格</div>
        <div class="body-value">¥ {{ item.payment.toFixed(2) }}</div>
      </div>
      <div class="body-row">
        <div class="body-label">创建时间</div>
        <div class="body-value tip">{{ dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss') }}</div>
      </div>
    </div>
    <!-- 1. 待支付：取消问诊+去支付 -->
    <div class="foot" v-if="item.status === OrderType.ConsultPay">
      <van-button
        class="gray"
        plain
        size="small"
        round
        @click="cancelConsult(item)"
        :loading="loading"
        >取消问诊</van-button
      >
      <van-button type="primary" plain size="small" round :to="`/user/consult/${item.id}`">
        去支付
      </van-button>
    </div>
    <!-- 2. 待接诊：取消问诊+继续沟通 -->
    <div class="foot" v-if="item.status === OrderType.ConsultWait">
      <van-button
        class="gray"
        plain
        size="small"
        round
        @click="cancelConsult(item)"
        :loading="loading"
        >取消问诊
      </van-button>
      <van-button type="primary" plain size="small" round :to="`/room?orderId=${item.id}`">
        继续沟通
      </van-button>
    </div>
    <!-- 3. 咨询中：查看处方（如果开了）+继续沟通 -->
    <div class="foot" v-if="item.status === OrderType.ConsultChat">
      <van-button
        v-if="item.prescriptionId"
        class="gray"
        plain
        size="small"
        round
        @click="showPrescription(item.prescriptionId)"
      >
        查看处方
      </van-button>
      <van-button type="primary" plain size="small" round :to="`/room?orderId=${item.id}`">
        继续沟通
      </van-button>
    </div>
    <!-- 4. 已完成：更多（查看处方，如果开了，删除订单）+问诊记录+（未评价?写评价:查看评价） -->
    <div class="foot" v-if="item.status === OrderType.ConsultComplete">
      <div class="more">
        <van-popover
          placement="top-start"
          v-model:show="showPopover"
          :actions="actions"
          @select="(action) => onSelect(action, item)"
        >
          <template #reference> 更多 </template>
        </van-popover>
      </div>
      <van-button class="gray" plain size="small" round :to="`/room?orderId=${item.id}`">
        问诊记录
      </van-button>
      <van-button
        v-if="!item.evaluateId"
        type="primary"
        plain
        size="small"
        round
        :to="`/room?orderId=${item.id}`"
      >
        去评价
      </van-button>
      <van-button v-else class="gray" plain size="small" round :to="`/room?orderId=${item.id}`">
        查看评价
      </van-button>
    </div>
    <!-- 5. 已取消：删除订单+咨询其他医生 -->
    <div class="foot" v-if="item.status === OrderType.ConsultCancel">
      <van-button class="gray" plain size="small" round @click="deleteOrder(item)"
        >删除订单</van-button
      >
      <van-button type="primary" plain size="small" round to="/">咨询其他医生</van-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.consult-item {
  border-radius: 4px;
  box-shadow: 0px 0px 22px 0px rgba(245, 245, 245, 0.1);
  background-color: #fff;
  margin-bottom: 10px;
  .head {
    display: flex;
    align-items: center;
    height: 50px;
    padding: 0 15px;
    .img {
      width: 20px;
      height: 20px;
    }
    > p {
      flex: 1;
      font-size: 15px;
      padding-left: 10px;
    }
    > span {
      color: var(--cp-tag);
      &.orange {
        color: #f2994a;
      }
      &.green {
        color: var(--cp-primary);
      }
    }
  }
  .body {
    padding: 15px 15px 8px 15px;
    .body-row {
      display: flex;
      margin-bottom: 7px;
    }
    .body-label {
      width: 62px;
      font-size: 13px;
      color: var(--cp-tip);
    }
    .body-value {
      width: 250px;
      color: var(--cp-price);
      &.tip {
        color: var(--cp-text2);
      }
    }
  }
  .foot {
    padding: 0 15px 15px 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .van-button {
      margin-left: 10px;
      padding: 0 16px;
      &.gray {
        color: var(--cp-text3);
        background-color: var(--cp-bg);
      }
    }
    .more {
      color: var(--cp-tag);
      flex: 1;
      font-size: 13px;
    }
  }
}
</style>
